import { onBeforeUnmount, watch } from 'vue'
import { useAppStore } from '@/stores'
import { Echarts } from '.'

type EchartsType = InstanceType<typeof Echarts>

export const useResize = (echarts?: EchartsType) => {
  const echartsMap = new Map()

  // 窗口事件
  const resize = (_echarts?: EchartsType) => {
    if (_echarts) {
      echartsMap.set(_echarts, _echarts)
      return
    }
    let timer: NodeJS.Timeout
    const _resize = () => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        echarts?.resize()
      }, 10)
    }

    watch(
      () => useAppStore().sidebar.opened,
      () => {
        setTimeout(_resize, 310)
      }
    )
    window.addEventListener('resize', _resize, false)

    onBeforeUnmount(() => {
      echarts?.dispose()
      window.removeEventListener('resize', _resize)
    })
  }

  // 卸载
  const uninstall = () => {
    echartsMap.forEach((item: EchartsType) => {
      // dom 存在则执行
      if (item.Echarts.getDom()) {
        item?.dispose()
      }
    })

    window.removeEventListener('resize', windowResize)
  }

  // 窗口事件
  const windowResize = () => {
    echartsMap.forEach((item: EchartsType) => {
      // dom 存在则执行
      if (item.Echarts.getDom()) {
        item?.resize()
      } else {
        echartsMap.delete(item)
      }
    })
  }

  // 未传 示例 则注册卸载
  if (!echarts) {
    // 注册事件
    window.addEventListener('resize', windowResize, false)

    watch(
      () => useAppStore().sidebar.opened,
      () => {
        setTimeout(windowResize, 310)
      }
    )
    onBeforeUnmount(() => {
      uninstall()
    })
  }

  return {
    resize
  }
}
